import React, {Component} from 'react';
import PropTypes from 'prop-types';
import GoBack from "@/components/TheGoBack";
import {
    Descriptions,
    Image,
    Space,
    Button,
    Badge,
    Tooltip,
    Modal,
    Form,
    Input,
    InputNumber,
    Row,
    Col,
    Divider, message,Select
} from "antd";
import TheImage from '@/components/TheImage'
import DebounceSelect from "@/components/DebounceSelect"
import {
    apiPetCheckDetails,
    apiPetCheckReject,
    apiPetCheckEchoDimension,
    apiPetCheckDetailPass,
} from '@/request/petDistinguish/distinguish';
import {
    apiSpeciesPageOne
} from '@/request/petDistinguish/breed';

//监听文本框，禁止输入回车和空格
const handleKeydown=(e)=>{
    if(e.keyCode===32 || e.keyCode===13){
        e.preventDefault();
        return;
    }
}

class FormVD extends React.Component {
    render() {
        let {data} = this.props;
        let dom = data.map((item, index) => {
            let vt = {}
            if (item.dimension === null){
                return ''
            }
            if (item.dimension.length > 0) {
                vt = item.dimension.map((v, i) => {
                    return <>
                        <Form.Item label={v.manageName}  rules={[{required: true}]}
                                   name={['petCheckDetailList', index, 'petCheckDetail', i, 'manageText']}>
                            <Input.TextArea onKeyDown={(e)=>handleKeydown(e)} placeholder={'请输入50字以内的评价'} showCount maxLength={50} rows={3}/>
                        </Form.Item>
                        <Form.Item style={{display: 'none'}} label="manageName"
                                   name={['petCheckDetailList', index, 'petCheckDetail', i, 'manageName']}
                                   initialValue={v.manageName}>
                            <Input/>
                        </Form.Item>
                        <Form.Item style={{display: 'none'}} label="manageLevel"
                                   name={['petCheckDetailList', index, 'petCheckDetail', i, 'manageLevel']}
                                   initialValue={v.manageLevel}>
                            <Input/>
                        </Form.Item>
                        <Form.Item style={{display: 'none'}} label="canDelete"
                                   name={['petCheckDetailList', index, 'petCheckDetail', i, 'canDelete']}
                                   initialValue={v.canDelete}>
                            <Input/>
                        </Form.Item>
                    </>
                })
            }
            return <>
                <Form.Item label={<><span style={{color: 'red',marginRight: 5}}>*</span>{item.manageName}</>} key={'vo-' + index}>
                    {!item.canDelete && <Row gutter={8}>
                        <Col flex="55%">
                            <Form.Item
                                name={['petCheckDetailList', index, 'manageScore']}
                                noStyle
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入评分',
                                    },
                                ]}
                            >
                                <InputNumber min={0} max={100} precision={0} addonAfter={'分'}
                                             placeholder="请输入评分"/>
                            </Form.Item>
                        </Col>
                        <Col flex="44%">
                            <Form.Item name={['petCheckDetailList', index, 'scoreRatio']} style={{marginBottom: 0}}
                                       initialValue={item.scoreRatio}>
                                <span className="ant-form-text">评分占比为{item.scoreRatio}%</span>
                                {/*<Input suffix="%" bordered={false} readOnly/>*/}
                            </Form.Item>
                        </Col>
                    </Row>}
                </Form.Item>
                <Form.Item style={{display: 'none'}} label="manageName" name={['petCheckDetailList', index, 'manageName']}
                           initialValue={item.manageName}>
                    <Input/>
                </Form.Item>
                <Form.Item style={{display: 'none'}} label="manageLevel" name={['petCheckDetailList', index, 'manageLevel']}
                           initialValue={item.manageLevel}>
                    <Input/>
                </Form.Item>
                <Form.Item style={{display: 'none'}} label="canDelete" name={['petCheckDetailList', index, 'canDelete']}
                           initialValue={item.canDelete}>
                    <Input/>
                </Form.Item>
                {vt}
            </>
        })
        return <>
            {dom}
        </>
    }
}


class Details extends Component {
    constructor(prop) {
        super(prop);
        this.FormRefBack = React.createRef()
        this.FormRefReport = React.createRef()
        this.state = {
            backVisible: false,
            reportVisible: false,
            petCheckId: prop.match.params.id,
            dataSource: {},
            vDataSource: [],
            vDom: [],
            options: []
        }
    }

    componentDidMount() {
        this.getData()
    }

    getData = () => {
        apiPetCheckDetails({
            petCheckId: this.state.petCheckId
        }).then(res => {
            if (res.code === 0 && res.data) {
                let vDom = []
                if (res.data.petCheckDetails) {
                    res.data.petCheckDetails.forEach((item) => {
                        let dom = [];
                        if (item.petCheckDetail) {
                            item.petCheckDetail.forEach(i => {
                                // str += (i.manageName+":"+(i.manageText??'-'))+'\n'
                                // if (item.manageScore){
                                    dom.push(<div>{i.manageName}：{i.manageText ?? '-'}</div>)
                                // }
                                // else {
                                //     dom.push(<div>{i.manageText ?? '-'}</div>)
                                // }
                            })
                        }
                        vDom.push(
                            {
                                name: item.manageName + (item.manageScore!==null?"(" + item.manageScore + "分):":':'),
                                text: dom,
                            }
                        )
                    })
                }
                this.setState({
                    dataSource: res.data,
                    vDom
                })
            }
        })
    }
    openBackModal = () => {
        this.setState({
            backVisible: true
        })
    }
    //  驳回
    onBackFinish = () => {
        this.FormRefBack.current.validateFields().then(values => {
            apiPetCheckReject({
                petCheckId: this.state.petCheckId,
                ...values
            }).then(res => {
                if (res.code === 0) {
                    message.success('驳回成功')
                    this.onBackCancel()
                    this.getData()
                }
            })
        })
    }
    onBackCancel = () => {
        this.setState({
            backVisible: false
        })
    }
    // 字段值更新时触发回调事件
    onValuesChange = (changedValues, allValues) => {
        let count = 0
        allValues.petCheckDetailList.forEach(item=>{
            if ('manageScore' in item){
                count += ((item.manageScore??0) * (item.scoreRatio/100))
            }
        })
        if (count > 100){
            count = 100
        }
        let values = this.FormRefReport.current.getFieldsValue()
        values.petCheck.totalScore = Math.round(count)
        this.FormRefReport.current.setFieldsValue({...values})
    }
    // 防抖模糊搜索
    fetchList = (value) => {
        return apiSpeciesPageOne({
            type: this.state.dataSource.petType,
            speciesName: value
        }).then(res => {
            if (res.code === 0) {
                return res.data.map((item, index) => ({
                    label: item.speciesName,
                    value: item.petSpeciesId,
                    key: index
                }))
            }
        })
    }
    openReportModal = () => {
        this.setState({
            reportVisible: true
        }, () => {
            apiPetCheckEchoDimension({
                manageType: this.state.dataSource.petType
            }).then(res => {
                if (res.code === 0) {
                    this.setState({
                        vDataSource: res.data
                    })
                }
            })
            apiSpeciesPageOne({
                type: this.state.dataSource.petType,
                speciesName: ''
            }).then(res => {
                if (res.code === 0) {
                    let options = res.data.map((item, index) => ({
                        label: item.speciesName,
                        value: item.petSpeciesId,
                    }))
                    this.setState({
                        options
                    })
                    // return res.data.map((item, index) => ({
                    //     label: item.speciesName,
                    //     value: item.petSpeciesId,
                    //     key: index
                    // }))
                }
            })
        })
    }
    onReportCancel = () => {
        this.setState({
            reportVisible: false
        })
    }
    onReportFinish = () => {
        this.FormRefReport.current.validateFields().then(values => {
            let { petCheckId, dataSource} = this.state
            values.petCheck.memberId = dataSource.memberId
            values.petCheck.id = dataSource.id
            values.petCheck.petCheckId = petCheckId
            values.petCheck.checkSource = dataSource.checkSource
            values.petCheck.petSpeciesName = values.petCheck.petSpeciesName.label
            // console.log(values)
            apiPetCheckDetailPass({...values}).then(res=>{
                if (res.code === 0){
                    // this.onReportCancel()
                    message.success('操作成功')
                    // this.getData()
                    this.props.history.goBack(-1)
                }
            })
        })
    }
    render() {
        let { formdata,backVisible, reportVisible, dataSource, vDom, vDataSource,count,options} = this.state;
        let extra = '';
        switch (dataSource.checkStatus) {
            case 0:
                extra = <Badge status="processing" text={<span>待鉴别</span>}/>
                break;
            case 1:
                extra = <Badge status="success" text={'鉴别成功-' + (dataSource.lockStatus ? '已解锁' : '未解锁')}/>
                break;
            case 2:
                extra = <Badge status="error" text={
                    <Tooltip title={dataSource.checkFailReason} placement="bottom">
                        <span>鉴别失败</span>
                    </Tooltip>
                }/>
                break;
            default:
                break;
        }
        return (
            <div className="p-layout-box">
                <GoBack history={this.props.history} title={'详情'} extra={extra}/>
                <div className={'p-layout-box'}>
                    <Space direction="vertical" size={'large'} style={{width: '45%'}}>
                        <Descriptions title={'鉴别信息'} column={1} bordered
                                      labelStyle={{width: 150, textAlign: 'center'}}>
                            <Descriptions.Item label="鉴别类型:">{dataSource.petType ? '猫猫' : '狗狗'}</Descriptions.Item>
                            <Descriptions.Item label="鉴别图片:">
                                <Image.PreviewGroup>
                                    {
                                        dataSource.petImages && dataSource.petImages.split(',').map((item, index) => {
                                            return <TheImage key={index} src={item} width={80} height={80}/>
                                        })
                                    }
                                </Image.PreviewGroup>
                            </Descriptions.Item>
                            <Descriptions.Item label="提交时间:">{dataSource.createTime}</Descriptions.Item>
                            {
                                dataSource.checkStatus !== 0 && <>
                                    <Descriptions.Item label="鉴别时间:">{dataSource.updateTime}</Descriptions.Item>
                                    <Descriptions.Item label="鉴别人:">{dataSource.updateName}</Descriptions.Item>
                                </>
                            }
                        </Descriptions>
                        <Descriptions title={'用户信息'} column={1} bordered
                                      labelStyle={{width: 150, textAlign: 'center'}}>
                            <Descriptions.Item label="用户昵称:">{dataSource.nickName}</Descriptions.Item>
                            <Descriptions.Item label="用户ID:">{dataSource.memberId}</Descriptions.Item>
                        </Descriptions>
                        {
                            dataSource.petArchivesId && <Descriptions title={'宠物档案'} column={1} bordered
                                                                      labelStyle={{width: 150, textAlign: 'center'}}>
                                <Descriptions.Item label="头像:">
                                    <TheImage src={dataSource.petCardShowImages} width={80} height={80}/>
                                </Descriptions.Item>
                                <Descriptions.Item label="品种:">{dataSource.petVarieties}</Descriptions.Item>
                                <Descriptions.Item label="出生日期:">{dataSource.birthday}</Descriptions.Item>
                                <Descriptions.Item label="体重(kg):">{dataSource.weight}kg</Descriptions.Item>
                                <Descriptions.Item
                                    label="性别:">{dataSource.petSex === 1 ? '弟弟' : '妹妹'}</Descriptions.Item>
                                <Descriptions.Item
                                    label="绝育情况:">{dataSource.sterilizationStatus === 'Y' ? '已绝育' : '未绝育'}</Descriptions.Item>
                            </Descriptions>
                        }
                        {
                            dataSource.checkStatus === 1 && <Descriptions title={'鉴定结果'} column={1} bordered
                                                                          labelStyle={{width: 150, textAlign: 'center'}}>
                                <Descriptions.Item label="综合评分:">{dataSource.totalScore}分</Descriptions.Item>
                                {
                                    vDom.map((item, index) => {
                                        return <Descriptions.Item key={"vd-" + index} label={item.name}>
                                            {item.text.map((d) => d)}
                                        </Descriptions.Item>
                                    })
                                }
                                <Descriptions.Item
                                    label="综合评价:">{dataSource.comprehensiveEvaluation}</Descriptions.Item>
                            </Descriptions>
                        }
                    </Space>
                    <br/>
                    {
                        dataSource.checkStatus === 0 && <Space size={'large'} style={{width: '100%', justifyContent: 'center'}}>
                            <Button size={'large'} onClick={this.openBackModal}>
                                驳回鉴别
                            </Button>
                            <Button type="primary" onClick={this.openReportModal} size={'large'}>
                                出具鉴别报告
                            </Button>
                        </Space>
                    }
                </div>
                <Modal
                    title={'驳回鉴别'}
                    visible={backVisible}
                    maskClosable={false}
                    onCancel={() => this.onBackCancel()}
                    onOk={() => this.onBackFinish()}
                >
                    <Form
                        name="basic"
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 14,
                        }}
                        ref={this.FormRefBack}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="请输入原因"
                            name="checkFailReason"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入原因',
                                },
                            ]}
                        >
                            <Input.TextArea placeholder={'请告诉用户鉴别失败的原因'} showCount maxLength={100}
                                            rows={3}/>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal
                    title={'输入鉴定报告'}
                    maskClosable={false}
                    visible={reportVisible}
                    style={{
                        left: '20%'
                    }}
                    width={600}
                    onCancel={() => this.onReportCancel()}
                    onOk={() => this.onReportFinish()}
                >
                    <Form
                        name="Report"
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 14,
                        }}
                        ref={this.FormRefReport}
                        autoComplete="off"
                        onValuesChange={this.onValuesChange}
                    >
                        <Form.Item
                            label="品种"
                            name={["petCheck", 'petSpeciesName']}
                            rules={[
                                {
                                    required: true,
                                    message: '请选择品种',
                                },
                            ]}
                        >
                            <Select
                                showSearch
                                placeholder="请选择品种"
                                optionFilterProp="children"
                                filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                                labelInValue={true}
                                options={options}
                            />

                            {/*<DebounceSelect*/}
                            {/*    showSearch*/}
                            {/*    placeholder="输入关键字查询"*/}
                            {/*    fetchOptions={this.fetchList}*/}
                            {/*    onChange={(newValue) => {*/}
                            {/*        console.log(newValue)*/}
                            {/*    }}*/}
                            {/*    style={{*/}
                            {/*        width: '100%',*/}
                            {/*    }}*/}
                            {/*/>*/}
                        </Form.Item>
                        <FormVD data={vDataSource}/>

                        <Divider/>
                        <Form.Item
                            label="综合评价"
                            name={["petCheck", 'comprehensiveEvaluation']}
                            rules={[
                                {
                                    required: true,
                                }
                            ]}
                        >
                            <Input.TextArea onKeyDown={(e)=>handleKeydown(e)}  placeholder={'请输入200字以内的评价'} showCount maxLength={200} rows={5}/>
                        </Form.Item>
                        <Form.Item
                            rules={[{required: true}]}
                            label="综合评分" name={["petCheck", 'totalScore']} initialValue={0}>
                            <Input value={count} bordered={false} readOnly/>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}

Details.propTypes = {};

export default Details;
